#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uv.h>

uv_loop_t *loop;
uv_tty_t tty;
uv_buf_t buf;

void on_read(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf) {
    if (nread > 0) {
        // 输出读取到的内容
        fwrite(buf->base, 1, nread, stdout);
        printf(" %02x\n", buf->base[0]);
        fflush(stdout);
        if (buf->base[0] == 'Q') {
            printf("\n[exit]\n");
            uv_stop(loop);
        }
    } else if (nread < 0) {
        // 处理错误或 EOF
        if (nread == UV_EOF) {
            printf("EOF reached\n");
        } else {
            fprintf(stderr, "Read error: %s\n", uv_strerror(nread));
        }
        uv_close((uv_handle_t *)stream, NULL);
    }
}

void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
    buf->base = malloc(suggested_size);
    buf->len = suggested_size;
}

int main() {
    loop = uv_default_loop();

    // 初始化 TTY
    if (uv_tty_init(loop, &tty, 0, 1) != 0) {
        fprintf(stderr, "Failed to initialize TTY\n");
        return 1;
    }

    // 设置为原始模式
    uv_tty_set_mode(&tty, UV_TTY_MODE_RAW);

    // 启动读取
    uv_read_start((uv_stream_t *)&tty, alloc_buffer, on_read);

    // 运行事件循环
    uv_run(loop, UV_RUN_DEFAULT);

    // 清理资源
    uv_tty_reset_mode();
    uv_close((uv_handle_t *)&tty, NULL);
    uv_loop_close(loop);
    free(buf.base);
    return 0;
}

